/*
 * @Author: 缄默
 * @Date: 2022-03-11 22:12:35
 * @LastEditors: 缄默
 * @LastEditTime: 2022-03-11 22:44:41
 */

//将整数字符串转换为整数值

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int strToInt(string& s1);
bool isValid(string& s1);

int main() {
    string s1 = "-123";
    string s2 = "2147483648";
    string s3 = "012";
    string s4 = "123";
    cout << strToInt(s1) << endl;    
    cout << strToInt(s2) << endl;    
    cout << strToInt(s3) << endl;    
    cout << strToInt(s4) << endl;    

    return 0;
}

int strToInt(string& s1) {
    if (!isValid(s1)) return 0;
    bool sign = true;
    int n = 0;
    int nextN = 0;

    auto iter = s1.begin();
    if (*iter == '-') {
        iter++;
        sign = false;
    }
    while (iter < s1.end()) {
        nextN = n * 10 - (*iter - '0');
        //判断是否越界
        if ((nextN + (*iter - '0')) / 10 != n) return 0;
        n = nextN;
        iter++;
    }
    if (n == -2147483648 && sign == true) return 0;
    return sign ? -n : n;
}

//有效返回true
bool isValid(string& s1) {
    if (s1.size() == 0) return false;

    //记录整数正负 true代表正；
    auto iter = s1.begin();
    if (*iter == '-') {
        iter++;
    }
    else if (*iter <= '0' || *iter > '9') return false;

    while (iter != s1.end()) {
        if (!(*iter >= '0' && *iter < '9')) return false;
        iter++;
    }
    return true;
}
